package com.virtium.vpm.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.virtium.vpm.exception.CryptoException;



/**
 * Provides encryption algorithms when dealing with passwords.
 * 
 * @author TuanAnh
 *
 */
public class SecurityUtil {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			System.out.println("TuanAnh" + hashPasswordMD5(hashPasswordMD5("123456")));
			System.out.println("----");
			System.out.println(isValidPassword("5f4dcc3b5aa765d61d8327deb882cf99","password"));
		} catch (CryptoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	/**
	 * This method checks if the encrypted password and the clear text
	 * password are the same.
	 * 
	 * @param encrypted
	 * @param password
	 * @return
	 * @throws CryptoException
	 */
	public static boolean isValidPassword(String encrypted, String password) throws CryptoException {
		return (encrypted.equals(hashPasswordMD5(password))?true:false);
	}

	/**
	 * This method will encrypt the clear text password into MD5 string.
	 * @param password
	 * @return
	 * @throws CryptoException
	 */
	public static String hashPasswordMD5(String password) throws CryptoException {
		if (password == null) {
			password = "";
		}
		byte[] buf = new byte[password.length()];
		buf = password.getBytes();

		MessageDigest algorithm = null;
		try {
			algorithm = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new CryptoException(CryptoException.ALGORITHM_EXP, e);
		}

		algorithm.reset();
		algorithm.update(buf);
		byte[] digest = algorithm.digest();
		return convertHex(digest);
	}

	private static String convertHex(byte[] bar) throws CryptoException {
		if (bar == null)
			throw new CryptoException("ERROR: null bar @ convertHex");
		String hex = "";
		for (int i = 0; i < bar.length; i++) {
			byte b = bar[i];
			if (b == 0) {
				hex = hex + "00";
			} else {
				String tmp = Integer.toHexString((int) b);
				if (tmp.length() == 1) {
					tmp = "0" + tmp;
				} else if (tmp.length() == 8) {
					tmp = tmp.substring(6);
				}
				hex = hex + tmp;
			}
		}
		return hex;
	}
}
